<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold;">报关单生成与申报</span>
        <div style="float: right;">
          <el-button 
            size="small" 
            type="primary" 
            icon="el-icon-plus"
            @click="handleSelectOrders"
            v-hasPermi="['fiscale:declaration:selectOrder']"
          >选择订单</el-button>
        </div>
      </div>

      <!-- 报关单基本信息 -->
      <el-form ref="declarationForm" :model="declarationForm" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="报关类型" prop="declarationType">
              <el-select v-model="declarationForm.declarationType" placeholder="请选择报关类型">
                <el-option
                  v-for="dict in dict.type.fiscale_declaration_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="贸易方式" prop="tradeMode">
              <el-select v-model="declarationForm.tradeMode" placeholder="请选择贸易方式">
                <el-option
                  v-for="dict in dict.type.fiscale_trade_mode"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运输方式" prop="transportMode">
              <el-select v-model="declarationForm.transportMode" placeholder="请选择运输方式">
                <el-option
                  v-for="dict in dict.type.fiscale_transport_mode"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="启运港" prop="departurePort">
              <el-input v-model="declarationForm.departurePort" placeholder="请输入启运港" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目的港" prop="destinationPort">
              <el-input v-model="declarationForm.destinationPort" placeholder="请输入目的港" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出口日期" prop="exportDate">
              <el-date-picker
                v-model="declarationForm.exportDate"
                type="date"
                placeholder="请选择出口日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="币种" prop="currency">
              <el-input v-model="declarationForm.currency" placeholder="请输入币种" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              <el-input v-model="declarationForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 已选订单列表 -->
      <div style="margin-top: 20px;">
        <h3>已选订单</h3>
        <el-table :data="selectedOrders" border style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="150" />
          <el-table-column prop="customerName" label="客户名称" width="150" />
          <el-table-column prop="totalAmount" label="总金额" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.totalAmount }} {{ scope.row.currency || 'USD' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalWeight" label="总重量" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.totalWeight }} KG</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.fiscale_order_status" :value="scope.row.orderStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="removeOrder(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 商品明细 -->
      <div style="margin-top: 20px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
          <h3>商品明细</h3>
          <el-button size="small" type="success" icon="el-icon-plus" @click="addProductRow">添加商品行</el-button>
        </div>

        <!-- 校验错误显示 -->
        <el-alert
          v-if="validationErrors.length > 0"
          title="数据校验失败"
          type="error"
          :closable="false"
          style="margin-bottom: 10px;"
        >
          <ul style="margin: 0; padding-left: 20px;">
            <li v-for="error in validationErrors" :key="error.field">
              <strong>{{ error.field }}:</strong> {{ error.message }}
            </li>
          </ul>
        </el-alert>

        <el-table :data="productList" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column label="商品名称" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="商品名称" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="英文名称" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productNameEn" placeholder="英文名称" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="HS编码" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.hsCode" placeholder="HS编码" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.specification" placeholder="规格型号" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" size="small" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="单位" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.unitPrice" :precision="2" :min="0" size="small" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="总价" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.totalPrice" :precision="2" :min="0" size="small" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="重量(KG)" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.weight" :precision="3" :min="0" size="small" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="原产国" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.countryOfOrigin" placeholder="原产国" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="品牌" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.brand" placeholder="品牌" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="型号" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.model" placeholder="型号" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button 
                size="mini" 
                type="text" 
                @click="autoFillProduct(scope.$index)"
                v-hasPermi="['fiscale:declaration:autoFill']"
              >智能填充</el-button>
              <el-button size="mini" type="text" style="color: #f56c6c;" @click="removeProduct(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 操作按钮 -->
      <div style="margin-top: 20px; text-align: center;">
        <el-button 
          type="primary" 
          @click="validateData"
          v-hasPermi="['fiscale:declaration:validate']"
        >校验</el-button>
        <el-button 
          type="info" 
          @click="saveDraft"
          v-hasPermi="['fiscale:declaration:saveDraft']"
        >保存为草稿</el-button>
        <el-button 
          type="danger" 
          @click="submitToCustoms"
          v-hasPermi="['fiscale:declaration:submit']"
        >申报</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>

    <!-- 订单选择器对话框 -->
    <el-dialog title="选择订单" :visible.sync="orderSelectorVisible" width="1200px" append-to-body>
      <OrderSelector 
        ref="orderSelector"
        @confirm="handleOrdersSelected"
        @cancel="orderSelectorVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { generateFromOrders, autoFillProductInfo, validateDeclaration, saveDraft, submitToCustoms } from "@/api/fiscale/declarationGenerate";
import OrderSelector from "./components/OrderSelector.vue";

export default {
  name: "DeclarationGenerate",
  dicts: ['fiscale_declaration_type', 'fiscale_trade_mode', 'fiscale_transport_mode', 'fiscale_order_status'],
  components: {
    OrderSelector
  },
  data() {
    return {
      // 报关单表单
      declarationForm: {
        declarationType: '',
        tradeMode: '',
        transportMode: '',
        departurePort: '',
        destinationPort: '',
        exportDate: '',
        currency: 'USD',
        remark: ''
      },
      // 已选订单
      selectedOrders: [],
      // 商品列表
      productList: [],
      // 订单选择器对话框
      orderSelectorVisible: false,
      // 校验错误
      validationErrors: [],
      // 表单验证规则
      rules: {
        declarationType: [
          { required: true, message: "报关类型不能为空", trigger: "change" }
        ],
        tradeMode: [
          { required: true, message: "贸易方式不能为空", trigger: "change" }
        ],
        transportMode: [
          { required: true, message: "运输方式不能为空", trigger: "change" }
        ],
        departurePort: [
          { required: true, message: "启运港不能为空", trigger: "blur" }
        ],
        destinationPort: [
          { required: true, message: "目的港不能为空", trigger: "blur" }
        ],
        exportDate: [
          { required: true, message: "出口日期不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.loadOrdersFromRoute();
  },
  methods: {
    /** 从路由参数加载订单 */
    loadOrdersFromRoute() {
      const orderIds = this.$route.query.orderIds;
      if (orderIds) {
        // 这里应该调用API获取订单详情
        console.log('从路由加载订单:', orderIds);
      }
    },

    /** 选择订单 */
    handleSelectOrders() {
      this.orderSelectorVisible = true;
    },

    /** 订单选择确认 */
    handleOrdersSelected(orders) {
      this.selectedOrders = orders;
      this.orderSelectorVisible = false;
      
      // 自动生成商品明细
      this.generateProductListFromOrders();
    },

    /** 根据订单生成商品明细 */
    generateProductListFromOrders() {
      this.productList = [];
      this.selectedOrders.forEach(order => {
        if (order.orderItems) {
          order.orderItems.forEach(item => {
            this.productList.push({
              productName: item.productName || '',
              productNameEn: item.productNameEn || '',
              hsCode: item.hsCode || '',
              specification: item.specification || '',
              quantity: item.quantity || 0,
              unit: item.unit || 'PCS',
              unitPrice: item.unitPrice || 0,
              totalPrice: item.totalPrice || 0,
              weight: item.weight || 0,
              countryOfOrigin: item.countryOfOrigin || '',
              brand: item.brand || '',
              model: item.model || '',
              productSku: item.productSku
            });
          });
        }
      });
    },

    /** 移除订单 */
    removeOrder(index) {
      this.selectedOrders.splice(index, 1);
      this.generateProductListFromOrders();
    },

    /** 添加商品行 */
    addProductRow() {
      this.productList.push({
        productName: '',
        productNameEn: '',
        hsCode: '',
        specification: '',
        quantity: 0,
        unit: 'PCS',
        unitPrice: 0,
        totalPrice: 0,
        weight: 0,
        countryOfOrigin: '',
        brand: '',
        model: '',
        productSku: ''
      });
    },

    /** 智能填充商品信息 */
    autoFillProduct(index) {
      const product = this.productList[index];
      if (!product.productSku && !product.productName) {
        this.$modal.msgWarning("请先输入商品SKU或商品名称");
        return;
      }

      const productSku = product.productSku || product.productName;
      autoFillProductInfo(productSku).then(response => {
        if (response.code === 200) {
          const data = response.data;
          Object.assign(this.productList[index], {
            productName: data.productName || product.productName,
            productNameEn: data.productNameEn || product.productNameEn,
            hsCode: data.hsCode || product.hsCode,
            specification: data.specification || product.specification,
            unit: data.unit || product.unit
          });
          this.$modal.msgSuccess("智能填充成功");
        } else {
          this.$modal.msgError(response.msg);
        }
      });
    },

    /** 移除商品 */
    removeProduct(index) {
      this.$modal.confirm('确定删除此商品行？').then(() => {
        this.productList.splice(index, 1);
      }).catch(() => {});
    },

    /** 数据校验 */
    validateData() {
      this.validationErrors = [];
      
      // 先验证基本表单
      this.$refs["declarationForm"].validate((valid) => {
        if (valid) {
          // 调用后端校验
          const declarationData = this.buildDeclarationData();
          validateDeclaration(declarationData).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("数据校验通过");
            } else {
              this.validationErrors = response.errors || [];
              this.$modal.msgError("数据校验失败，请检查错误信息");
            }
          });
        } else {
          this.$modal.msgError("请完善报关单基本信息");
        }
      });
    },

    /** 保存草稿 */
    saveDraft() {
      this.$refs["declarationForm"].validate((valid) => {
        if (valid) {
          const declarationData = this.buildDeclarationData();
          saveDraft(declarationData).then(response => {
            this.$modal.msgSuccess("草稿保存成功");
            // 可以跳转到报关单列表或继续编辑
          });
        } else {
          this.$modal.msgError("请完善报关单基本信息");
        }
      });
    },

    /** 申报到海关 */
    submitToCustoms() {
      this.$modal.confirm('确认向海关单一窗口申报此报关单？申报后不可修改。').then(() => {
        // 先保存草稿
        const declarationData = this.buildDeclarationData();
        saveDraft(declarationData).then(response => {
          // 从响应数据中提取declarationId
          let declarationId = null;
          if (response.data && typeof response.data === 'object') {
            declarationId = response.data.declarationId;
          } else {
            declarationId = response.data;
          }
          
          // 确保declarationId有效
          if (!declarationId) {
            this.$modal.msgError("未能获取到报关单ID");
            return;
          }
          
          // 再申报
          submitToCustoms(declarationId).then(submitResponse => {
            if (submitResponse.code === 200) {
              this.$modal.msgSuccess("申报成功：" + submitResponse.msg);
              // 提示用户订单状态已更新
              this.$modal.msgInfo("相关订单状态已更新为'报关中'");
              // 跳转到状态跟踪页面
              this.$router.push('/fiscale/customs/declaration/tracking');
            } else {
              this.$modal.msgError("申报失败：" + submitResponse.msg);
              if (submitResponse.errors) {
                this.validationErrors = submitResponse.errors;
              }
            }
          });
        });
      }).catch(() => {});
    },

    /** 构建报关单数据 */
    buildDeclarationData() {
      return {
        ...this.declarationForm,
        declarationOrderList: this.selectedOrders.map(order => ({
          orderId: order.orderId,
          orderNo: order.orderNo,
          orderAmount: order.totalAmount,
          orderWeight: order.totalWeight,
          orderPackages: order.totalQuantity
        })),
        declarationItemList: this.productList.map((item, index) => {
          // 查找该商品对应的订单和订单明细
          let orderId = null;
          let orderItemId = null;
          
          // 如果是从订单生成的，则查找对应的订单ID
          if (this.selectedOrders && this.selectedOrders.length > 0) {
            // 尝试通过productSku匹配
            if (item.productSku) {
              for (let order of this.selectedOrders) {
                if (order.orderItems) {
                  for (let orderItem of order.orderItems) {
                    if (orderItem.productSku === item.productSku) {
                      orderId = order.orderId;
                      orderItemId = orderItem.itemId;
                      break;
                    }
                  }
                  if (orderId) break;
                }
              }
            }
            
            // 如果还没找到，且只有一个订单，则默认关联到该订单
            if (!orderId && this.selectedOrders.length === 1) {
              orderId = this.selectedOrders[0].orderId;
              // 如果该订单有明细项，则关联到第一个明细项
              if (this.selectedOrders[0].orderItems && this.selectedOrders[0].orderItems.length > 0) {
                const orderItemIndex = Math.min(index, this.selectedOrders[0].orderItems.length - 1);
                orderItemId = this.selectedOrders[0].orderItems[orderItemIndex].itemId;
              }
            }
          }
          
          return {
            orderId: orderId,
            orderItemId: orderItemId,
            productName: item.productName,
            productNameEn: item.productNameEn,
            hsCode: item.hsCode,
            specification: item.specification,
            quantity: item.quantity,
            unit: item.unit,
            unitPrice: item.unitPrice,
            totalPrice: item.totalPrice,
            weight: item.weight,
            countryOfOrigin: item.countryOfOrigin,
            brand: item.brand,
            model: item.model
          };
        })
      };
    },

    /** 返回 */
    goBack() {
      this.$router.push('/fiscale/customs/declaration');
    }
  }
};
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

h3 {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
</style>